package com.blog.effective.note3;

import java.io.*;

/**
 * @author 张俊强~.
 * @func 对象输入输出流.
 * @date 2017/11/1 11:30.
 */
public class ObjectStreamDemo {

    public static void main(String[] args){

        // 使用不同的功能，注释另外一个功能即可
        try {
            ObjectStreamDemo.writeObjectToFile(new AccountInfo("45464@163.com","123456","厦门"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            AccountInfo accountInfo=(AccountInfo)ObjectStreamDemo.readObjectFromFile();
            System.out.println(accountInfo.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * @func 将对象持久化到文件中（序列化）
     * @throws java.io.IOException
     */
    public static void writeObjectToFile(AccountInfo accountInfo) throws IOException {

        //新建一个对象输出流
        ObjectOutputStream objectOutputStream=
                new ObjectOutputStream(new FileOutputStream("AccountInfo.txt"));
        //传入持久化对象
        objectOutputStream.writeObject(accountInfo);
        //关闭流
        objectOutputStream.close();
    }
    /**
     * @func 将对象从文件中读取（反序列化）.
     * @throws java.io.IOException
     */
    public static Object readObjectFromFile() throws IOException, ClassNotFoundException {
        //新建一个对象输入流
        ObjectInputStream objectInputStream=
                new ObjectInputStream(new FileInputStream("AccountInfo.txt"));
        //读取对象
        Object obj=objectInputStream.readObject();
        //关闭流
        objectInputStream.close();
        return obj;
    }

}

